package com.attendance.security.user.service;

import com.attendance.annotation.Supplement;
import com.attendance.annotation.type.OperationType;
import com.attendance.security.user.mapper.UserMapper;
import com.attendance.security.user.pojo.UserInfo;
import com.attendance.spring.SpringSecurityUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 用户服务
 *
 * @author 鵺丶
 * @date 2021/03/08
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    public UserInfo getUser(){
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", SpringSecurityUtils.getUserName());
        return userMapper.selectOne(wrapper);
    }

    public UserInfo selectByName(String name){
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", name);
        return userMapper.selectOne(wrapper);
    }

    public Long register(UserInfo userInfo) throws Exception {
        userInfo.setPassword(passwordEncoder.encode(userInfo.getPassword()));
        userMapper.insert(userInfo);
        return userInfo.getUserId();
    }

    public Boolean matchPassword(UserInfo userInfo, String password) {
        return passwordEncoder.matches(password, userInfo.getPassword());
    }

    @Supplement(type = OperationType.UPDATE)
    public Boolean updatePassword(UserInfo userInfo) {
        userInfo.setPassword(passwordEncoder.encode(userInfo.getPassword()));
        return userMapper.updateById(userInfo) != 0;
    }
}
